import frappe

def patch_model():
    """为达梦数据库打补丁模型相关功能"""
    print("为达梦数据库打补丁模型相关功能...")
    patch_delete_fields()

def patch_delete_fields():
    """为达梦数据库打补丁 delete_fields 函数"""
    print("为达梦数据库打补丁 delete_fields 函数...")
    import frappe.model
    original_delete_fields = frappe.model.delete_fields

    def patched_delete_fields(args_dict, delete=0):
        """修补后的 delete_fields 函数，支持达梦数据库
        
        Args:
            args_dict: 包含要删除字段的字典 {doctype: [fieldnames]}
            delete: 是否删除数据/列
        """
        import frappe.utils

        for dt in args_dict:
            fields = args_dict[dt]
            if not fields:
                continue

            frappe.db.delete(
                "DocField",
                {
                    "parent": dt,
                    "fieldname": ("in", fields),
                },
            )

            # Delete the data/column only if delete is specified
            if not delete:
                continue

            if frappe.db.get_value("DocType", dt, "issingle"):
                frappe.db.delete(
                    "Singles",
                    {
                        "doctype": dt,
                        "field": ("in", fields),
                    },
                )
            else:
                existing_fields = frappe.db.describe(dt)
                existing_fields = existing_fields and [e[0] for e in existing_fields] or []
                fields_need_to_delete = set(fields) & set(existing_fields)
                if not fields_need_to_delete:
                    continue

                # mariadb implicitly commits before DDL, make it explicit
                if frappe.db.db_type == "mariadb":
                    frappe.db.commit()

                # 根据数据库类型使用不同的标识符引号
                if frappe.db.db_type == "dm":
                    query = 'ALTER TABLE "tab{}" {}'.format(
                        dt,
                        ", ".join('DROP COLUMN "{}"'.format(f) for f in fields_need_to_delete)
                    )
                else:
                    query = "ALTER TABLE `tab{}` {}".format(
                        dt,
                        ", ".join("DROP COLUMN `{}`".format(f) for f in fields_need_to_delete)
                    )

                frappe.db.sql(query)

                # postgres and dm need to commit DDL explicitly
                if frappe.db.db_type in ("postgres", "dm"):
                    frappe.db.commit()

    # 应用补丁
    frappe.model.delete_fields = patched_delete_fields
